package com.demo.dao.impl;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.demo.dao.UserDao;
import com.demo.entity.User;

public class MybatisUserDaoImpl implements UserDao {

	private static SqlSession sqlSession = null;

	public SqlSession getSqlSession() {
		if (sqlSession == null) {
			InputStream is = MybatisUserDaoImpl.class.getClassLoader().getResourceAsStream(
					"mybatis.xml");
			SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
					.build(is);
			sqlSession = sessionFactory.openSession();
		}
		return sqlSession;
	}

	@Override
	public int insertUser(User user) {
		return getSqlSession().insert("insertUser", user);
	}

	@Override
	public int insertUsers(List<User> users) {
		return getSqlSession().insert("insertUsers", users);
	}

	@Override
	public int updateUser(User user) {
		return getSqlSession().update("updateUser", user);
	}

	@Override
	public int delete(User user) {
		return getSqlSession().delete("deleteUser", user);
	}

	@Override
	public List<User> selectUsers(User user) {
		return getSqlSession().selectList("selectAllUser");
	}

	@Override
	public User selectUser(User user) {
		return getSqlSession()
				.selectOne("selectByPrimaryKey", user.getUserId());
	}

}
